# -*-coding:utf-8-*-
from PIL import Image, ImageDraw, ImageFont
import string, random
from io import BytesIO

str_all = string.digits + string.ascii_letters


# 生成随机颜色
def random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def random_code(size=(184, 44), length=4, point=500, line=10):
    width, height = size
    # 生成一个200*40的白色图片
    img = Image.new('RGB', (width, height), color=(255, 255, 255))
    # 生成一个和图片同大小的画布
    draw = ImageDraw.Draw(img)
    # 生成字体对象
    font = ImageFont.truetype(font='static/my/font/AaLiFangTi.ttf', size=30, )
    # 生成文字
    valid_code = ''
    for i in range(length):
        random_char = random.choice(str_all)
        draw.text((30 + 40 * i, 5), random_char, (0, 0, 0), font=font)
        valid_code += random_char

    # 随即生成点
    for i in range(point):
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.point((x, y), random_color())
    # 生成随机线
    for i in range(line):
        x1, y1 = random.randint(0, width), random.randint(0, height)
        x2, y2 = random.randint(0, width), random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=random_color())

    # 创建一个内存句柄
    f = BytesIO()
    # 保存到内存句柄中
    img.save(f, 'PNG')
    # 读取内存句柄
    data = f.getvalue()
    return (data, valid_code)
